<?php

namespace Utuo;

use Think\Model;

/**
 * 解决管理权限问题
 */
class UtuoModel extends Model {
	// 当前具有管理权限的ID
	protected $adminId = 0;
	
	// 数据表中标识记录所有者的字段
	protected $adminField = null;
	
	// 构造函数
	public function __construct($name = '', $tablePrefix = '', $connection = '') {
		parent::__construct($name, $tablePrefix, $connection);
		$this->adminId = session('id');
		$this->adminField = $this->adminField?$this->adminField:C("AUTH_FIELD");
	}
	
	// 插入数据前的回调方法
	protected function _before_insert(&$data,$options) {
		parent::_before_insert($data, $options);
		if (!$this->adminId) {
			return false;
		}
		$data[$this->adminField] = $this->adminId;
		return true;
	}
	
	// 更新前加上权限条件
	protected function _before_update(&$data, &$options) {
		if (!$this->adminId) {
			return false;
		}
		$options['where'][$this->adminField] = $this->adminId;
		return parent::_before_update($data, $options);
	}
	
	// 删除前加上权限条件
	protected function _before_delete(&$options) {
		$options['where'][$this->adminField] = $this->adminId;
		return parent::_before_delete($options);
	}
	
	// 合并save和add方法
	public function submit($data = '', $options = '') {
		$_POST[$this->adminField] = $this->adminId;
		empty($_POST['id']) and C('TOKEN_ON', true);
		if (parent::create()){
			return empty($_POST['id']) ? parent::add($data,$options): parent::save($data,$options);
		} else {
			return false;
		}
		
	}
	
	// 通过id获得数据
	public function getOneById() {
		$id=I('id','','intval');
		return $this->where(array(
				$this->adminField => $this->adminId,
				"id" => $id
		))->find();
		
	}
	
	/**
	 * 转化为批量更新数据
	 * @param array $update
	 * array(
	 *		'15' => array(
	 *			'name' => '2',
	 *			'age' => '2',
	 *		),
	 *		'16' => array(
	 *			'name' => '3',
	 *		),
	 *	);
	 * @return $data
	 * array(2) {
	 *	  "name" => array('exp', "CASE id WHEN 15 THEN '2' WHEN 16 THEN '3' END"),
	 *	  "age" => array('exp', "CASE id WHEN 15 THEN '2' END"),
	 *	}
	 */
	public static function batchUpdateData( $update ) {
		$j = 0;
		$data = array();
		$fieldsArray = array();
		foreach ( $update as $id => $fields ) {
			foreach ( $fields as $field => $value ) {
				if ( !$fieldsArray[$field] ) {
					$fieldsArray[$field] = array('CASE id');
				}
				$fieldsArray[$field][] = "WHEN $id THEN '$value'";
				if ( $j == count($update) - 1 ) {
					$fieldsArray[$field][] = "END";
				}
			}
			$j++;
		}
		foreach ( $fieldsArray as $field => $v ) {
			$data[$field] = array('exp', join(' ', $v));
		}
		return $data;
	}
	
}